
package net.acoder.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

/**
 * 
 * @author Daniel
 * @date 2009-11-20 上午10:39:45
 * 
 */
public class IOUtil {
    public static void copy(InputStream in, OutputStream out)
            throws IOException {
        byte[] buf = new byte[1024 * 1024];
        int length = -1;
        while ((length = in.read(buf)) != -1) {
            out.write(buf, 0, length);
        }
    }

    public static void fileCopy(String src, String dest) throws IOException {
        FileInputStream fis = new FileInputStream(src);
        FileOutputStream fos = new FileOutputStream(dest);
        copy(fis, fos);
        fis.close();
        fos.close();
    }

    public static void download(String urlStr, String folder)
            throws IOException {
        URL url = new URL(urlStr);
        String filename = urlStr.substring(urlStr.lastIndexOf('/'));
        File dir = new File(folder);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dir, filename);

        InputStream in = url.openStream();
        FileOutputStream fos = new FileOutputStream(file);
        copy(in, fos);
        in.close();
        fos.close();
    }
}
